import 'dart:ffi';

import 'package:animated_search_bar/animated_search_bar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:fwanandroid/model/api/WanAndroidService.dart';
import 'package:fwanandroid/model/bean/Article.dart';
import 'package:fwanandroid/ui/MyColors.dart';
import 'package:fwanandroid/ui/views/ArticleItemWidget.dart';

class SearchResultPage extends StatefulWidget {
  const SearchResultPage({super.key});

  @override
  State<SearchResultPage> createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  var isInit = false;
  String searchText = '';
  final TextEditingController _controller = TextEditingController(text: '');
  late EasyRefreshController _listController;
  int _currentPage = 0;
  List<Article> _articles = [];

  @override
  void initState() {
    super.initState();
    _listController = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    if(!isInit){
      isInit = true;
      var key = (ModalRoute.of(context)!.settings.arguments as String?);
      searchText = key == null ? "" : key;
      loadArticles(0);
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: MyColors.leiMuBlue,
        title: AnimatedSearchBar(
            label: searchText.isEmpty ? '请输入内容' : searchText,
            controller: _controller,
            labelStyle: const TextStyle(fontSize: 16),
            searchStyle: const TextStyle(color: Colors.white),
            cursorColor: Colors.white,
            textInputAction: TextInputAction.done,
            searchDecoration: const InputDecoration(
              hintText: 'Search',
              alignLabelWithHint: true,
              fillColor: Colors.white,
              focusColor: Colors.white,
              hintStyle: TextStyle(color: Colors.white70),
              border: InputBorder.none,
            ),
            onChanged: (value) {
              debugPrint('value on Change');
              setState(() {
                searchText = value;
              });
            },
            onFieldSubmitted: (value) {
              debugPrint('value on Field Submitted');
              setState(() {
                searchText = value;
              });
              loadArticles(0);
            }),
      ),
      body: Container(
        color: Colors.white,
        child: EasyRefresh.builder(
            controller: _listController,
            header: const MaterialHeader(),
            footer: const ClassicFooter(),
            onRefresh: () async {
              loadArticles(0);
            },
            onLoad: () async {
              loadArticles(_currentPage + 1);
            },
            childBuilder: (context, physics) {
              return CustomScrollView(
                physics: physics,
                slivers: [
                  SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      return ArticleItemWidget(article: _articles[index]);
                    }, childCount: _articles.length),
                  )
                ],
              );
            }),
      ),
    );
  }

  loadArticles(page) {
    WanAndroidService.searchHot(page, searchText).then((value) {
      setState(() {
        _currentPage = page;
        if (page == 0) {
          _articles = value.datas;
        } else {
          _articles.addAll(value.datas);
        }
      });
      _listController.finishRefresh();
      _listController.resetFooter();
      _listController.finishLoad(value.curPage >= value.pageCount
          ? IndicatorResult.noMore
          : IndicatorResult.success);
    });
  }
}
